package com.wlcb.jpower.chat.service.impl;

import com.wlcb.jpower.chat.api.DingdingApi;
import com.wlcb.jpower.chat.pojo.dingding.DRequest;
import com.wlcb.jpower.chat.service.DingdingService;
import com.wlcb.jpower.properties.JpowerChatProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @author: liwenfei
 * @version: v1.0
 * @time: 2021/3/2 15:24
 * @desc:
 */
@Slf4j
@Service("dingdingServiceImpl")
public class DingdingServiceImpl implements DingdingService {

    private static final String secret = "SEC44cb89f25faecf5722c79c1c277d4c43fdd1af665d7648adf6696f54ed5277f3";

    @Resource
    private DingdingApi dingdingApi;
    @Autowired
    private JpowerChatProperties properties;

    @Async("threadPool")
    @Override
    public Boolean sendEx(DRequest request) {
        Long timestamp = System.currentTimeMillis();
        String sign = sign(timestamp);
        String result = dingdingApi.msgSend(properties.getDingDingToken(),timestamp, sign, request);
        log.info("DRequest:{},result:{}", request.toString(), result);
        return result.contains("ok");
    }

    private static String sign(Long timestamp) {
        try {
            String stringToSign = timestamp + "\n" + secret;
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
            return URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
